#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2025/4/8 14:12
# @Author  : 梁满仓
# @File    : stock_5_min_hist_data_of_000300.py
# @Software: PyCharm


import pandas as pd
import requests
import json
import os

# 沪深300指数（sh000300）5分钟K线
url = "http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData?symbol=sh000300&scale=5&datalen=1000"

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
}

try:
    # 1. 获取数据
    response = requests.get(url, headers=headers)
    response.raise_for_status()  # 检查请求是否成功

    data = json.loads(response.text)
    df = pd.DataFrame(data)

    # 2. 数据处理
    # 转换时间格式并拆分为date和time
    df['datetime'] = pd.to_datetime(df['day'])
    df['date'] = df['datetime'].dt.date  # 提取日期部分
    df['time'] = df['datetime'].dt.time  # 提取时间部分

    # 选择需要的列并转换数据类型
    df = df[['date', 'time', 'open', 'high', 'low', 'close', 'volume']].astype({
        'open': float,
        'high': float,
        'low': float,
        'close': float,
        'volume': float
    })

    # 3. 保存为CSV
    csv_path = "沪深300_5分钟数据.csv"
    df.to_csv(csv_path, encoding='utf_8_sig', index=False)  # index=False不保存行索引

    print(f"数据已成功保存至：{os.path.abspath(csv_path)}")
    print("前5行数据预览：")
    print(df.head())

except Exception as e:
    print("程序出错：", e)
    if 'response' in locals():
        print("HTTP状态码：", response.status_code)
        print("返回数据片段：", response.text[:200])